<script setup>
import { ref, onMounted, defineEmits } from 'vue'
import { useArticleStore, useTypeStore } from '@/stores/index.js'
import { useAddArtService, useSetArtService } from '@/api/request.js'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage } from 'element-plus'

// 分类仓库
const typeStore = useTypeStore()

// 文章仓库
const articleStore = useArticleStore()

onMounted(async () => {
  await typeStore.getTypeList()
})

// 增加 | 修改 文章 抽屉实例
const drawerRef = ref()
// 隐藏 | 显示 标记变量
const isShow = ref(false)

// 标题
const title = ref('')

// 表单实例
const form = ref()

// 表单数据
const formData = ref({
  id: '',
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
})

// 表单校验
const rules = {
  title: [
    {
      required: true,
      message: '标题不能为空',
      trigger: 'blur'
    },
    {
      pattern: /^\S{5,10}$/,
      message: '标题字数应在5-10位',
      trigger: 'blur'
    }
  ],
  cate_id: [
    {
      required: true,
      message: '请选择分类',
      trigger: 'blur'
    }
  ],
  cover_img: {
    required: true,
    message: '封面是必须的',
    trigger: 'blur'
  },
  content: {
    required: true,
    message: '内容不能为空',
    trigger: 'blur'
  }
}

// 富文本框实例
const quill = ref()
// 抽屉关闭前的回调
const handleClose = () => {
  formData.value = {
    id: '',
    title: '',
    cate_id: '',
    content: '',
    cover_img: '',
    state: ''
  }
  title.value = '添加文章'
  imgUrl.value = ''
  // 重置表单数据无法清除富文本内容  手动调用富文本实例清空内容
  quill.value.setText('')
}

//  对外暴露 open方法用于控制抽屉的显示类型 增加 | 修改
const open = async (data) => {
  // 携带id 视为修改
  if (data.id) {
    title.value = '修改文章'
    // 获取修改回显
    await articleStore.getArtDetail(data.id)
    formData.value = { ...articleStore.article }
    // 处理图片地址
    imgUrl.value = formData.value.cover_img
  } else {
    title.value = '增加文章'
  }

  isShow.value = true
}

defineExpose({
  open
})

const emits = defineEmits(['success'])

// 点击草稿 | 增加 按钮的回调
const onSave = async (state) => {
  //校验表单
  await form.value.validate()
  // 设置提交状态
  formData.value.state = state
  // 封装表单数据
  const data = new FormData()
  for (let key in formData.value) {
    data.append(key, formData.value[key])
  }
  // 没有携带id 增加操作
  if (!formData.value.id) {
    // 提交后台数据
    await useAddArtService(data)
    ElMessage.success(state === 'add' ? '增加成功' : '保持成功')
  } else {
    // 通过url加载图片数据
    const avatar = await fetch(formData.value.cover_img)
    // 将图片数据转换为 blob
    const blob = await avatar.blob()
    // 利用 blob对象 创建 基于 url 的图片File对象
    const file = new File([blob], formData.value.cover_img, { type: blob.type })

    data.set('cover_img', file)

    await useSetArtService(data)
    ElMessage.success('修改成功')
  }
  // 通知父组件 添加 | 修改成功
  emits('success')
  isShow.value = false
}

// 上传框实例
const upload = ref()

// 图片数据 响应数据
const imgUrl = ref('')
// 当上传图片时的回调
const onUploadFile = (uploadFile) => {
  console.log(uploadFile.raw)
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  formData.value.cover_img = uploadFile.raw
}
</script>

<template>
  <el-drawer
    ref="drawerRef"
    v-model="isShow"
    :title="title"
    direction="rtl"
    class="demo-drawer"
    size="50vw"
    @close="handleClose"
  >
    <div class="demo-drawer__content">
      <el-form
        :model="formData"
        :rules
        ref="form"
        class="drawer-form"
        style="width: 80%"
      >
        <el-form-item prop="title" label="文章标题" label-width="80px">
          <el-input
            autocomplete="off"
            size="large"
            placeholder="请输入标题"
            v-model="formData.title"
          />
        </el-form-item>
        <el-form-item prop="cate_id" label="文章分类" label-width="80px">
          <el-select
            size="large"
            placeholder="请选择分类"
            v-if="typeStore.typeList"
            v-model="formData.cate_id"
          >
            <el-option
              v-for="item in typeStore.typeList"
              :label="item.cate_name"
              :value="item.id"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img" label-width="80px">
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="onUploadFile"
            ref="upload"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容" prop="content" label-width="80px">
          <div class="editor">
            <quill-editor
              theme="snow"
              v-model:content="formData.content"
              contentType="html"
              ref="quill"
            >
            </quill-editor>
          </div>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button type="primary" @click="onSave('已发布')">发布</el-button>
        <el-button type="info" @click="onSave('草稿')">草稿</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.demo-drawer__footer {
  padding-left: 80px;
}
</style>
